<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryFormRef" :model="queryParams" :inline="true" class="search-form">
      <el-form-item label="优惠券" prop="couponId" class="search-item">
        <el-select v-model="queryParams.couponId" placeholder="请选择优惠券" clearable>
          <el-option v-for="item in couponOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status" class="search-item">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item class="search-item">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['coupon:exchange:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['coupon:exchange:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['coupon:exchange:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
          >删除</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="exchangeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column label="规则ID" align="center" prop="id" width="80" />
      <el-table-column label="优惠券名称" align="left" prop="couponName" min-width="180" :show-overflow-tooltip="true" />
      <el-table-column label="所需积分" align="center" prop="points" width="100">
        <template #default="scope">
          <el-tag type="warning">{{ scope.row.points }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="兑换上限" align="center" prop="exchangeLimit" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.exchangeLimit === -1 ? 'info' : 'success'">
            {{ scope.row.exchangeLimit === -1 ? '不限' : scope.row.exchangeLimit + '次' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" min-width="200">
        <template #default="scope">
          <div class="time-wrapper">
            <div class="time-item">
              <span class="time-label">开始：</span>
              <span class="time-value">{{ scope.row.startTime }}</span>
            </div>
            <div class="time-item">
              <span class="time-label">结束：</span>
              <span class="time-value">{{ scope.row.endTime }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="120" fixed="right">
        <template #default="scope">
          <div class="status-wrapper">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              :loading="scope.row.statusLoading"
              @change="handleStatusChange(scope.row)"
            />
            <span class="status-text" :class="{ 'is-active': scope.row.status === 1 }">
              {{ scope.row.status === 1 ? '已启用' : '已禁用' }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button-group>
            <el-button v-hasPermi="['coupon:exchange:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-hasPermi="['coupon:exchange:remove']" link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />

    <!-- 添加或修改积分兑换规则对话框 -->
    <el-dialog v-model="open" :title="title" width="600px" append-to-body>
      <el-form ref="exchangeFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="优惠券" prop="couponId">
          <el-select v-model="form.couponId" placeholder="请选择优惠券" style="width: 100%">
            <el-option v-for="item in couponOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所需积分" prop="points">
          <el-input-number v-model="form.points" :min="1" :controls="false" style="width: 200px" />
        </el-form-item>
        <el-form-item label="兑换上限" prop="exchangeLimit">
          <el-input-number v-model="form.exchangeLimit" :min="-1" :controls="false" style="width: 200px" />
          <span class="ml-2">-1表示不限次数</span>
        </el-form-item>
        <el-form-item label="有效期" prop="validTime">
          <el-date-picker
            v-model="validTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            style="width: 100%"
            @change="handleValidTimeChange"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="0">未启用</el-radio>
            <el-radio :value="1">已启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="规则描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入规则描述" :maxlength="200" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listExchange, getExchange, addExchange, updateExchange, delExchange } from '@/api/coupon/exchange';
import { listTemplate } from '@/api/coupon/template';
import type { PointsExchangeRuleQuery, PointsExchangeRuleVO, PointsExchangeRuleForm } from '@/api/coupon/exchange/types';
import type { FormInstance, FormRules } from 'element-plus';

// 状态选项
const statusOptions = [
  { value: 0, label: '未启用' },
  { value: 1, label: '已启用' },
  { value: 2, label: '已结束' }
];

// 优惠券选项
const couponOptions = ref<{ id: number; name: string }[]>([]);

const loading = ref(false);
const showSearch = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const exchangeList = ref<PointsExchangeRuleVO[]>([]);
const open = ref(false);
const title = ref('');
const validTime = ref<[string, string] | null>(null);
const exchangeFormRef = ref();

const queryParams = reactive<PointsExchangeRuleQuery>({
  pageNum: 1,
  pageSize: 10,
  couponId: undefined,
  status: undefined
});

const form = reactive<PointsExchangeRuleForm>({
  couponId: undefined,
  points: 1,
  exchangeLimit: -1,
  startTime: '',
  endTime: '',
  status: 0,
  description: ''
});

const rules = reactive<FormRules>({
  couponId: [{ required: true, message: '优惠券不能为空', trigger: 'change' }],
  points: [
    { required: true, message: '所需积分不能为空', trigger: 'blur' },
    { type: 'number', min: 1, message: '所需积分必须大于0', trigger: 'blur' }
  ],
  exchangeLimit: [{ required: true, message: '兑换上限不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
});

/** 查询积分兑换规则列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listExchange(queryParams);
    if (res.code === 200) {
      exchangeList.value = res.rows.map((item) => ({
        ...item,
        statusName: item.status === 0 ? '未启用' : item.status === 1 ? '已启用' : '已结束',
        statusLoading: false
      }));
      total.value = res.total;
    }
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.couponId = undefined;
  queryParams.status = undefined;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PointsExchangeRuleVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = '添加积分兑换规则';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: PointsExchangeRuleVO) => {
  reset();

  const id = row?.id || ids.value[0];
  const res = await getExchange(id);

  form.id = res.data.id;
  form.couponId = res.data.couponId;
  form.points = res.data.points;
  form.exchangeLimit = res.data.exchangeLimit;
  form.status = res.data.status;
  form.startTime = res.data.startTime;
  form.endTime = res.data.endTime;
  validTime.value = [form.startTime, form.endTime];

  open.value = true;
  title.value = '修改积分兑换规则';
};

/** 提交按钮 */
const submitForm = async () => {
  if (!exchangeFormRef.value) return;

  await exchangeFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      let res;
      if (form.id) {
        res = await updateExchange(form);
      } else {
        res = await addExchange(form);
      }
      if (res.code === 200) {
        ElMessage.success(form.id ? '修改成功' : '新增成功');
        open.value = false;
        getList();
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: PointsExchangeRuleVO) => {
  const id = row?.id || ids.value[0];
  await ElMessageBox.confirm('是否确认删除积分兑换规则编号为"' + id + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });
  const res = await delExchange(id);
  if (res.code === 200) {
    ElMessage.success('删除成功');
    getList();
  }
};

/** 表单重置 */
const reset = () => {
  form.id = undefined;
  form.couponId = undefined;
  form.points = 1;
  form.exchangeLimit = -1;
  form.startTime = '';
  form.endTime = '';
  form.status = 0;
  form.description = '';
  validTime.value = null;
};

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  reset();
};

/** 有效期变更 */
const handleValidTimeChange = (val: [string, string] | null) => {
  if (val) {
    form.startTime = val[0];
    form.endTime = val[1];
  } else {
    form.startTime = '';
    form.endTime = '';
  }
};

/** 加载优惠券选项 */
const loadCouponOptions = async () => {
  const res = await listTemplate({
    pageNum: 1,
    pageSize: 100,
    status: 1
  });
  if (res.code === 200) {
    couponOptions.value = res.rows.map((item) => ({
      id: item.id,
      name: item.name
    }));
  }
};

/** 修改兑换码状态 */
const handleStatusChange = (row: PointsExchangeRuleVO) => {
  const text = row.status === 1 ? '启用' : '停用';
  row.statusLoading = true;
  updateExchange({
    id: row.id,
    couponId: row.couponId,
    points: row.points,
    exchangeLimit: row.exchangeLimit,
    startTime: row.startTime,
    endTime: row.endTime,
    status: row.status,
    description: row.description
  })
    .then(() => {
      ElMessage.success(text + '成功');
    })
    .catch(() => {
      row.status = row.status === 1 ? 0 : 1;
    })
    .finally(() => {
      row.statusLoading = false;
    });
};

onMounted(() => {
  getList();
  loadCouponOptions();
});
</script>

<style scoped>
.ml-2 {
  margin-left: 8px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
  padding: 20px;
  background-color: var(--el-bg-color);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
}

.search-item {
  margin-bottom: 0;
  margin-right: 0;
}

.search-item :deep(.el-form-item__label) {
  width: 80px;
  text-align: right;
  padding-right: 8px;
}

.search-item :deep(.el-input),
.search-item :deep(.el-select) {
  width: 200px;
}

.status-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.status-text {
  font-size: 13px;
  color: #909399;

  &.is-active {
    color: #67c23a;
  }
}

.time-wrapper {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 4px 0;
}

.time-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.time-label {
  color: #909399;
  font-size: 13px;
}

.time-value {
  color: var(--el-text-color-primary);
  font-size: 13px;
}

:deep(.el-switch) {
  --el-switch-on-color: #67c23a;
  --el-switch-off-color: #f56c6c;
}

:deep(.el-table) {
  --el-table-border-color: var(--el-border-color-lighter);
  --el-table-header-bg-color: var(--el-bg-color-page);
}

:deep(.el-table th) {
  font-weight: 600;
  background-color: var(--el-bg-color-page);
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button-group) {
  display: flex;
  gap: 8px;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}
</style>
